package com.example.leero.graduation.activity;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.leero.graduation.API;
import com.example.leero.graduation.App;
import com.example.leero.graduation.BaseActivity;
import com.example.leero.graduation.R;
import com.example.leero.graduation.Util.DateUtil;
import com.example.leero.graduation.Util.StringUtil;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;

public class PublishActivity extends BaseActivity implements View.OnClickListener{

    private EditText et_title, et_content, et_number, et_sport_address;
    private TextView tv_run_setting, tv_sport_type, tv_sport_time;
    private Button btn_number_unlimited, btn_sex_unlimited, btn_man, btn_women;

    private String sexSelected = "0";
    private String numLimit = "0";
    private String sportSelected = "0";

    @Override
    protected int getLayoutId() {
        return R.layout.activity_publish;
    }

    @Override
    protected void initVariable() {
        et_title = (EditText) findViewById(R.id.et_title);
        et_content = (EditText) findViewById(R.id.et_content);
        et_number = (EditText) findViewById(R.id.et_number);
        et_sport_address = (EditText) findViewById(R.id.et_sport_address);

        tv_run_setting = (TextView) findViewById(R.id.tv_run_setting);
        tv_sport_type = (TextView) findViewById(R.id.tv_sport_type);
        tv_sport_time = (TextView) findViewById(R.id.tv_sport_time);

        btn_number_unlimited = (Button) findViewById(R.id.btn_number_unlimited);
        btn_sex_unlimited = (Button) findViewById(R.id.btn_sex_unlimited);
        btn_man = (Button) findViewById(R.id.btn_man);
        btn_women = (Button) findViewById(R.id.btn_women);
    }

    @Override
    protected void initView(Bundle state) {
        TextView title = (TextView) findViewById(R.id.tv_title);
        title.setText("发布约伴");
        tv_run_setting.setText("发布");
        tv_run_setting.setVisibility(View.VISIBLE);

        listen();
    }

    private void listen() {
        findViewById(R.id.iv_left).setOnClickListener(this);
        tv_run_setting.setOnClickListener(this);
        findViewById(R.id.btn_sex_unlimited).setOnClickListener(this);
        btn_sex_unlimited.setOnClickListener(this);
        btn_man.setOnClickListener(this);
        btn_women.setOnClickListener(this);
        btn_number_unlimited.setOnClickListener(this);
        findViewById(R.id.ll_sport_type).setOnClickListener(this);
        findViewById(R.id.ll_time).setOnClickListener(this);

        et_number.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (et_number.getText().toString().equals("")) {
                    btn_number_unlimited.setTextColor(getResources().getColor(R.color.background_btn_green));
                } else {
                    btn_number_unlimited.setTextColor(getResources().getColor(R.color.text_color_release_normal));
                    numLimit = et_number.getText().toString();
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_left:
                finish(); break;
            case R.id.tv_run_setting:
                postData(); break;
            case R.id.btn_sex_unlimited:
                changeSexSelected(0); break;
            case R.id.btn_man:
                changeSexSelected(1); break;
            case R.id.btn_women:
                changeSexSelected(2); break;
            case R.id.btn_number_unlimited:
                et_number.setText("");
                numLimit = "0"; break;
            case R.id.ll_sport_type:
                showSportDialog();
                break;
            case R.id.ll_time:
                showTimeDialog();
                break;

            default: break;
        }
    }

    private void changeSexSelected(int position) {
        if (position == 0) {
            btn_sex_unlimited.setTextColor(getResources().getColor(R.color.text_color_release_select));
            btn_man.setTextColor(getResources().getColor(R.color.text_color_release_normal));
            btn_women.setTextColor(getResources().getColor(R.color.text_color_release_normal));
        } else if (position == 1) {
            btn_man.setTextColor(getResources().getColor(R.color.text_color_release_select));
            btn_sex_unlimited.setTextColor(getResources().getColor(R.color.text_color_release_normal));
            btn_women.setTextColor(getResources().getColor(R.color.text_color_release_normal));
        } else if (position == 2) {
            btn_women.setTextColor(getResources().getColor(R.color.text_color_release_select));
            btn_sex_unlimited.setTextColor(getResources().getColor(R.color.text_color_release_normal));
            btn_man.setTextColor(getResources().getColor(R.color.text_color_release_normal));
        }
        sexSelected = position + "";
    }

    private void showSportDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(PublishActivity.this);
        builder.setIcon(R.drawable.a);
        builder.setTitle("选择一种活动");
        final String[] sports = {"跑步", "羽毛球", "篮球", "足球", "网球", "乒乓球", "自行车"};
        builder.setItems(sports, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                tv_sport_type.setText(sports[which]);
                sportSelected = (which + 1) + "";
            }
        });
        builder.show();
    }

    private void showTimeDialog() {
        android.app.AlertDialog alertDialog = new android.app.AlertDialog.Builder(this).create();
        alertDialog.show();
        Window window = alertDialog.getWindow();
        window.setContentView(R.layout.layout_time_dialog);
        window.setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));

        handleDialog(window, alertDialog);
    }

    private void handleDialog(final Window window, final android.app.AlertDialog dialog) {
        final String currentTime = getCurrentTimeString();
        final TextView tvDate = (TextView) window.findViewById(R.id.tv_date);
        tvDate.setText(currentTime.split(" ")[0]);
        final TextView tvStartTime = (TextView) window.findViewById(R.id.tv_start_time);
        tvStartTime.setText(currentTime.split(" ")[1]);
        final TextView tvEndTime = (TextView) window.findViewById(R.id.tv_end_time);
        tvEndTime.setText(currentTime.split(" ")[1]);
        tvDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String date = currentTime.split(" ")[0];
                int year = Integer.parseInt(date.split("/")[0]);
                int month = Integer.parseInt(date.split("/")[1]);
                int day = Integer.parseInt(date.split("/")[2]);
                new DatePickerDialog(PublishActivity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        tvDate.setText(String.format("%d-%d-%d",year,monthOfYear+1,dayOfMonth));
                    }
                },year,month-1,day).show();
            }
        });
        window.findViewById(R.id.ll_start_time).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TimePickerDialog(PublishActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tvStartTime.setText(String.format("%d:%d",hourOfDay,minute));
                    }
                    //0,0指的是时间，true表示是否为24小时，true为24小时制
                },0,0,true).show();
            }
        });
        window.findViewById(R.id.ll_end_time).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new TimePickerDialog(PublishActivity.this, new TimePickerDialog.OnTimeSetListener() {
                    @Override
                    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                        tvEndTime.setText(String.format("%d:%d",hourOfDay,minute));
                    }
                    //0,0指的是时间，true表示是否为24小时，true为24小时制
                },0,0,true).show();
            }
        });
        window.findViewById(R.id.btn_cancel).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        window.findViewById(R.id.btn_confirm).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                tv_sport_time.setText(tvDate.getText().toString() + " " + tvStartTime.getText().toString() + "~" + tvEndTime.getText().toString());
            }
        });
    }

    private String getCurrentTimeString() {
        return DateUtil.longToString(System.currentTimeMillis(), DateUtil.FORMAT_DATE1_TIME);
    }

    private void postData() {
        if(!checkInput()) {
            new AlertDialog.Builder(PublishActivity.this)
                    .setMessage("请完善活动信息")
                    .setPositiveButton("确认", null)
                    .show();
            return;
        }

        OkHttpUtils.post().url(API.PUBLISH_ACTIVITY)
                .addParams("user_id", App.getLoginUser().id + "")
                .addParams("sport", sportSelected).addParams("title", et_title.getText().toString())
                .addParams("sport_time", tv_sport_time.getText().toString())
                .addParams("address", et_sport_address.getText().toString())
                .addParams("limit_number", numLimit).addParams("limit_sex", sexSelected)
                .addParams("content", et_content.getText().toString())
                .build().execute(new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    if (jsonObject.getBoolean("state")) {
                        Intent intent = new Intent(PublishActivity.this, DetailActivity.class);
                        intent.putExtra("id", jsonObject.getInt("id"));
                        intent.putExtra("isNew", true);
                        startActivity(intent);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    private Boolean checkInput() {
        if (!StringUtil.isEmpty(et_title.getText().toString()) &&
                !StringUtil.isEmpty(tv_sport_type.getText().toString()) &&
                !StringUtil.isEmpty(tv_sport_time.getText().toString()) &&
                !StringUtil.isEmpty(et_sport_address.getText().toString()) &&
                !StringUtil.isEmpty(et_content.getText().toString())) {
            return true;
        }

        return false;
    }
}
